import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import { getLocalData } from "@/utils/data-cache";
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/auth-redirect', '/404', '/401', '/505']; // 路由白名单，未登录可访问

router.beforeEach(async (to, from, next) => {

  NProgress.start(); //顶部页面加载进度条

  //document.title = getPageTitle(to.meta.title); //页面标题

  const theme = getLocalData('theme'); //设置主题
  store.dispatch('settings/changeTheme', theme);

  //获取系统标题配置
  //store.dispatch('settings/getSysSetting');

  const hasToken = getToken();
  if (hasToken) {
    if (to.path === '/login') {
      //登录后，不再显示登录页面，重定向至内容根路径
      next({ path: '/' });
      NProgress.done()
    } else {

      //获取系统标题配置
      // store.dispatch('settings/getSysSetting');

      //获取用户基本信息
      store.dispatch('user/getInfo');

      //判断登录用户是否有菜单权限
      const hasRoles = store.getters.menu_count > 0;

      if (hasRoles) {
        next()
      } else {
        //获取当前账号菜单权限
        const menus = await store.dispatch('user/getSystemAuth');
        if (menus.length === 0) {
          Message.error("当前账号无系统使用权限，请联系管理员分配权限");
          store.dispatch('user/clearUserAuth');
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        } else {
          const accessRoutes = await store.dispatch('permission/generateRoutes', menus);
          //动态添加有权限路由
          router.addRoutes(accessRoutes);
          //数据字典
          await store.dispatch('dictionary/getFullDictionary');
          //网络资源基础路径
          //store.dispatch('settings/setBasePath');
          next({ ...to, replace: true })
        }
      }
    }
  } else {
    //未登录，无token
    if (whiteList.indexOf(to.path) !== -1) {
      //白名单中路由可直接访问
      next()
    } else {
      // 权限限制路由则重定向到登录页
      next(`/login?redirect=${to.path}`);
      NProgress.done()
    }
  }
});

router.afterEach(() => {
  NProgress.done()
});
